using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model.Material;
using WPF_MVVM_Test.Services.Material;

namespace WPF_MVVM_Test.MVVM_ViewModel.Material
{
    /// <summary>
    /// 物料管理ViewModel
    /// </summary>
    public class MaterialManagementViewModel : BaseViewModel
    {
        private readonly MaterialService _materialService;
        private ObservableCollection<MVVM_Model.Material.Material> _materialItems;
        private string _materialNameFilter = string.Empty;
        private string _materialNumberFilter = string.Empty;
        private string _categoryFilter = string.Empty;
        private bool _isLoading = false;
        private int _currentPage = 1;
        private int _totalPages = 1;
        private int _pageSize = 10;
        private int _totalItems = 0;
        private string _jumpToPage = "1";

        public MaterialManagementViewModel()
        {
            // 初始化服务
            _materialService = new MaterialService();
            
            // 初始化集合
            _materialItems = new ObservableCollection<MVVM_Model.Material.Material>();

            // 初始化命令
            SearchCommand = CreateCommand(ExecuteSearch);
            RefreshCommand = CreateCommand(ExecuteRefresh);
            AddMaterialCommand = CreateCommand(ExecuteAddMaterial);
            EditMaterialCommand = CreateCommand<MVVM_Model.Material.Material>(ExecuteEditMaterial);
            
            // 分页命令
            FirstPageCommand = CreateCommand(ExecuteFirstPage, CanExecuteFirstPage);
            PreviousPageCommand = CreateCommand(ExecutePreviousPage, CanExecutePreviousPage);
            NextPageCommand = CreateCommand(ExecuteNextPage, CanExecuteNextPage);
            LastPageCommand = CreateCommand(ExecuteLastPage, CanExecuteLastPage);
            GoToPageCommand = CreateCommand(ExecuteGoToPage);

            // 加载数据
            LoadMaterialsAsync();
        }

        #region 属性

        /// <summary>
        /// 物料列表
        /// </summary>
        public ObservableCollection<MVVM_Model.Material.Material> MaterialItems
        {
            get => _materialItems;
            set => SetProperty(ref _materialItems, value);
        }

        /// <summary>
        /// 物料名称过滤条件
        /// </summary>
        public string MaterialNameFilter
        {
            get => _materialNameFilter;
            set => SetProperty(ref _materialNameFilter, value);
        }

        /// <summary>
        /// 物料编号过滤条件
        /// </summary>
        public string MaterialNumberFilter
        {
            get => _materialNumberFilter;
            set => SetProperty(ref _materialNumberFilter, value);
        }

        /// <summary>
        /// 分类过滤条件
        /// </summary>
        public string CategoryFilter
        {
            get => _categoryFilter;
            set => SetProperty(ref _categoryFilter, value);
        }

        /// <summary>
        /// 是否正在加载
        /// </summary>
        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        /// <summary>
        /// 当前页码
        /// </summary>
        public int CurrentPage
        {
            get => _currentPage;
            set
            {
                if (SetProperty(ref _currentPage, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                    UpdatePageCommands();
                }
            }
        }

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPages
        {
            get => _totalPages;
            set
            {
                if (SetProperty(ref _totalPages, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                    UpdatePageCommands();
                }
            }
        }

        /// <summary>
        /// 每页大小
        /// </summary>
        public int PageSize
        {
            get => _pageSize;
            set => SetProperty(ref _pageSize, value);
        }

        /// <summary>
        /// 总记录数
        /// </summary>
        public int TotalItems
        {
            get => _totalItems;
            set
            {
                if (SetProperty(ref _totalItems, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                }
            }
        }

        /// <summary>
        /// 跳转页码
        /// </summary>
        public string JumpToPage
        {
            get => _jumpToPage;
            set => SetProperty(ref _jumpToPage, value);
        }

        /// <summary>
        /// 分页信息
        /// </summary>
        public string PageInfo => $"共 {TotalItems} 条记录，第 {CurrentPage}/{TotalPages} 页";

        #endregion

        #region 命令

        public ICommand SearchCommand { get; }
        public ICommand RefreshCommand { get; }
        public ICommand AddMaterialCommand { get; }
        public ICommand EditMaterialCommand { get; }

        // 分页命令
        public ICommand FirstPageCommand { get; }
        public ICommand PreviousPageCommand { get; }
        public ICommand NextPageCommand { get; }
        public ICommand LastPageCommand { get; }
        public ICommand GoToPageCommand { get; }

        #endregion

        #region 命令执行方法

        private async void ExecuteSearch()
        {
            CurrentPage = 1;
            await LoadMaterialsAsync();
        }

        private async void ExecuteRefresh()
        {
            MaterialNameFilter = string.Empty;
            MaterialNumberFilter = string.Empty;
            CategoryFilter = string.Empty;
            CurrentPage = 1;
            await LoadMaterialsAsync();
        }

        private void ExecuteAddMaterial()
        {
            var dialog = new WPF_MVVM_Test.MVVM_View.Material.MaterialAddDialog();
            var result = dialog.ShowDialog();
            
            if (result == true)
            {
                // 新增成功后刷新列表
                ExecuteRefresh();
            }
        }

        private void ExecuteEditMaterial(MVVM_Model.Material.Material material)
        {
            if (material != null)
            {
                // TODO: 打开编辑物料对话框
                System.Windows.MessageBox.Show($"编辑物料：{material.MaterialName}\nID: {material.Id}", "物料详情", 
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
            }
        }

        #endregion

        #region 分页方法

        private async void ExecuteFirstPage()
        {
            CurrentPage = 1;
            await LoadMaterialsAsync();
        }

        private async void ExecutePreviousPage()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                await LoadMaterialsAsync();
            }
        }

        private async void ExecuteNextPage()
        {
            if (CurrentPage < TotalPages)
            {
                CurrentPage++;
                await LoadMaterialsAsync();
            }
        }

        private async void ExecuteLastPage()
        {
            CurrentPage = TotalPages;
            await LoadMaterialsAsync();
        }

        private async void ExecuteGoToPage()
        {
            if (int.TryParse(JumpToPage, out int pageNumber))
            {
                if (pageNumber >= 1 && pageNumber <= TotalPages)
                {
                    CurrentPage = pageNumber;
                    await LoadMaterialsAsync();
                }
            }
        }

        private bool CanExecuteFirstPage() => CurrentPage > 1;
        private bool CanExecutePreviousPage() => CurrentPage > 1;
        private bool CanExecuteNextPage() => CurrentPage < TotalPages;
        private bool CanExecuteLastPage() => CurrentPage < TotalPages;

        private void UpdatePageCommands()
        {
            (FirstPageCommand as RelayCommand)?.RaiseCanExecuteChanged();
            (PreviousPageCommand as RelayCommand)?.RaiseCanExecuteChanged();
            (NextPageCommand as RelayCommand)?.RaiseCanExecuteChanged();
            (LastPageCommand as RelayCommand)?.RaiseCanExecuteChanged();
        }

        private void UpdatePagination()
        {
            TotalPages = (int)Math.Ceiling((double)TotalItems / PageSize);
            if (CurrentPage > TotalPages && TotalPages > 0)
            {
                CurrentPage = TotalPages;
            }
        }

        #endregion

        #region 数据加载

        /// <summary>
        /// 加载物料数据
        /// </summary>
        private async System.Threading.Tasks.Task LoadMaterialsAsync()
        {
            IsLoading = true;
            
            try
            {
                var response = await _materialService.GetMaterialsByCategoryAsync(
                    categoryId: CategoryFilter,
                    pageIndex: CurrentPage,
                    pageSize: PageSize
                );

                if (response.IsSuc)
                {
                    MaterialItems.Clear();
                    
                    // 根据搜索条件过滤数据
                    var filteredData = response.Data.Data.AsEnumerable();
                    
                    if (!string.IsNullOrEmpty(MaterialNameFilter))
                    {
                        filteredData = filteredData.Where(m => m.MaterialName.Contains(MaterialNameFilter, StringComparison.OrdinalIgnoreCase));
                    }
                    
                    if (!string.IsNullOrEmpty(MaterialNumberFilter))
                    {
                        filteredData = filteredData.Where(m => m.MaterialNumber.Contains(MaterialNumberFilter, StringComparison.OrdinalIgnoreCase));
                    }

                    foreach (var item in filteredData)
                    {
                        MaterialItems.Add(item);
                    }

                    TotalItems = response.Data.TotalCount;
                    TotalPages = response.Data.TotalPage;
                    UpdatePagination();
                }
                else
                {
                  /*  System.Windows.MessageBox.Show($"加载物料数据失败：{response.Msg}", "错误", 
                        System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                    */
                    // 如果API失败，加载测试数据
                    LoadTestData();
                }
            }
            catch (Exception ex)
            {
                /*System.Windows.MessageBox.Show($"加载物料数据异常：{ex.Message}", "错误", 
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                */
                // 异常时加载测试数据
                LoadTestData();
            }
            finally
            {
                IsLoading = false;
            }
        }

        /// <summary>
        /// 加载测试数据（备用）
        /// </summary>
        private void LoadTestData()
        {
            MaterialItems.Clear();

            // 创建测试数据，匹配API返回的数据结构
            var testData = new[]
            {
                new MVVM_Model.Material.Material
                {
                    Id = "48c19b28-20f3-4b40-9696-243770b7b5e7",
                    MaterialNumber = "PVC-AUTO-002",
                    MaterialName = "汽车内饰软PVC薄膜",
                    SpecificationModel = "1.2mm×1500mm",
                    Unit = "平方米",
                    MaterialType = 1,
                    MaterialProperty = "外购",
                    MaterialCategoryId = "3d91bbf6-5a50-49e8-8bde-49908d92e804",
                    MaterialCategoryName = "汽车用硬 PVC",
                    Status = "启用"
                },
                new MVVM_Model.Material.Material
                {
                    Id = "0050bdd4-c2d3-4c0a-9075-9ed8b800fa40",
                    MaterialNumber = "PVC-ELE-001",
                    MaterialName = "电气用硬PVC管",
                    SpecificationModel = "Φ20×2.0mm",
                    Unit = "米",
                    MaterialType = 1,
                    MaterialProperty = "外购",
                    MaterialCategoryId = "b928523c-5a6a-41ed-88fa-287dd3ca5ba0",
                    MaterialCategoryName = "电气用硬 PVC",
                    Status = "启用"
                }
            };

            foreach (var item in testData)
            {
                MaterialItems.Add(item);
            }

            TotalItems = MaterialItems.Count;
            TotalPages = 1;
            UpdatePagination();
        }

        #endregion
    }
}